<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
        <el-button class="filter-item" type="primary"  @click="newAdd" >添加</el-button>
        <el-button class="filter-item" type="primary"  @click="edit" >修改</el-button>
        <el-button class="filter-item" type="primary"  @click="deleteMenu" >删除</el-button>
    </div>
    <div class="tree-container" style="width:25%;">
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText">
      </el-input>
      <el-tree
        class="filter-tree"
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        node-key="id"
        highlight-current
        accordion
        :filter-node-method="filterNode"
        @node-click="getNodeData"
        ref="menuTree">
      </el-tree>
    </div>
    <!--新增模态框-->
    <el-dialog :visible.sync="addDialogFormVisible">
      <el-form :rules="addRules" ref="ruleForm1" :model="ruleForm1" label-position="left" label-width="80px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="父菜单" prop="addParentName">
          <el-input v-model.trim="addParentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model.trim="ruleForm1.menuName"></el-input>
        </el-form-item>
        <el-form-item label="菜单编码"  prop="menuCode">
          <el-input v-model.trim="ruleForm1.menuCode"/>
        </el-form-item>
        <el-form-item label="菜单URL"  prop="url">
          <el-input v-model.trim="ruleForm1.url"/>
        </el-form-item>
        <el-form-item label="排序"  prop="number">
          <el-input-number v-model.trim="ruleForm1.number" controls-position="right" :min="1" :max="100"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model.trim="ruleForm1.status" label="1">启用</el-radio>
          <el-radio v-model.trim="ruleForm1.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddForm('ruleForm1')">保存</el-button>
        <el-button @click="resetForm('ruleForm1')">取消</el-button>
      </div>
    </el-dialog>

    <!--新增模态框-->
    <el-dialog :visible.sync="editDialogFormVisible">
      <el-form :rules="editRules" ref="ruleForm2" :model="ruleForm2" label-position="left" label-width="80px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="父菜单" prop="editParentName">
          <el-input v-model.trim="editParentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model.trim="ruleForm2.menuName"></el-input>
        </el-form-item>
        <el-form-item label="菜单编码"  prop="menuCode">
          <el-input v-model.trim="ruleForm2.menuCode"/>
        </el-form-item>
        <el-form-item label="菜单URL"  prop="url">
          <el-input v-model.trim="ruleForm2.url"/>
        </el-form-item>
        <el-form-item label="排序"  prop="number">
          <el-input-number v-model.trim="ruleForm2.number" controls-position="right" :min="1" :max="100"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model.trim="ruleForm2.status" label="1">启用</el-radio>
          <el-radio v-model.trim="ruleForm2.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm('ruleForm2')">保存</el-button>
        <el-button @click="resetForm('ruleForm2')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuTree, deleteMenu, enableMenu, disableMenu, modifyMenu, saveMenu, checkMenuCode } from '@/api/menu'
import waves from '@/directive/waves' // 水波纹指令
import { isValidMenuName, isValidMenuCode } from '@/utils/validate'
export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    const validateMenuCode = (rule, value, callback) => {
      if (!isValidMenuCode(value)) {
        callback(new Error('菜单编码格式不合法'))
      } else {
        const param = {}
        param.menuCode = value
        if (this.dialogStatus === 'update') {
          param.menuId = this.ruleForm2.id
        }
        checkMenuCode(param).then(response => {
          if (response) {
            callback(new Error('菜单编码已存在'))
          } else {
            callback()
          }
        })
      }
    }
    const validateMenuName = (rule, value, callback) => {
      if (!isValidMenuName(value)) {
        callback(new Error('菜单名称格式不合法'))
      } else {
        callback()
      }
    }
    return {
      filterText: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      labelPosition: 'right',
      listQuery: {
        menuName: ''
      },
      listLoading: true,
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      dialogStatus: '',
      deleteMenuId: '',
      disabledMenu: '',
      downloadLoading: false,
      addParentName: '',
      ruleForm1: {
        pid: '',
        menuName: '',
        menuCode: '',
        url: '',
        status: '1',
        number: 1
      },
      editParentName: '',
      ruleForm2: {
        id: '',
        pid: '',
        parentName: '',
        menuName: '',
        menuCode: '',
        url: '',
        status: '1',
        number: 1
      },
      addRules: {
        menuName: [
          { required: true, message: '菜单名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '菜单名长度为2到20个字符', trigger: 'blur' },
          { validator: validateMenuName, trigger: 'blur' }
        ],
        menuCode: [
          { required: true, message: '菜单编码不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '请正确填写菜单编码,支持2-20个汉字', trigger: 'blur' },
          { validator: validateMenuCode, trigger: 'blur' }
        ],
        url: [
          { required: true, message: '菜单URL不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '请正确填写菜单URL,支持2-30个字符', trigger: 'blur' }
        ]
      },
      editRules: {
        menuName: [
          { required: true, message: '菜单名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '菜单名长度为2到20个字符', trigger: 'blur' },
          { validator: validateMenuName, trigger: 'blur' }
        ],
        menuCode: [
          { required: true, message: '菜单编码不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '请正确填写菜单编码,支持2-20个汉字', trigger: 'blur' },
          { validator: validateMenuCode, trigger: 'blur' }
        ],
        url: [
          { required: true, message: '菜单URL不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '请正确填写菜单URL,支持2-30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '启用',
        0: '禁用'
      }
      return statusMap[status]
    }
  },
  watch: {
    filterText(val) {
      this.$refs.menuTree.filter(val)
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getMenuTree(this.listQuery).then(response => {
        this.treeData = response
        this.listLoading = false
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.menuName.indexOf(value) !== -1
    },
    getNodeData(data) {
      console.log(data)
      // 新增
      this.ruleForm1.pid = data.id
      this.addParentName = data.menuName
      // 修改
      this.ruleForm2.id = data.id
      this.ruleForm2.pid = data.parentId
      this.editParentName = data.parentMenuName
      this.ruleForm2.menuCode = data.menuCode
      this.ruleForm2.menuName = data.menuName
      this.ruleForm2.url = data.url
      this.ruleForm2.number = data.number
      this.ruleForm2.status = data.status
      // 删除
      this.deleteMenuId = data.id
      // 节点禁用标识
      this.disabledMenu = data.disabled
    },
    newAdd() {
      if (this.ruleForm1.pid === '') {
        this.$message({
          showClose: true,
          duration: 3000,
          message: '请选择父菜单'
        })
        return false
      }
      this.addDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm1'].clearValidate()
      })
    },
    submitAddForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveMenu(this.ruleForm1).then(response => {
            if (response === 1) {
              this.resetForm(formName)
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.addDialogFormVisible = false
      this.editDialogFormVisible = false
    },
    edit(row) {
      if (this.ruleForm2.id === '') {
        this.$message({
          showClose: true,
          duration: 3000,
          message: '请选择修改的菜单'
        })
        return false
      }
      if (this.disabledMenu) {
        this.$message({
          showClose: true,
          duration: 3000,
          message: '该菜单不允许修改'
        })
        return false
      }
      this.dialogStatus = 'update'
      this.editDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm2'].clearValidate()
      })
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modifyMenu(this.ruleForm2).then(response => {
            if (response === 1) {
              this.resetForm(formName)
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },
    deleteMenu(row) {
      if (this.disabledMenu) {
        this.$message({
          showClose: true,
          duration: 3000,
          message: '该菜单不允许删除'
        })
        return false
      }
      this.$confirm(`确定删除该菜单吗？`, '删除提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        deleteMenu(this.deleteMenuId).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    enable(row) {
      this.$confirm(`确定启用菜单${row.menuName}吗？`, '启用提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        enableMenu(row.id).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '启用成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消启用'
        })
      })
    },
    disable(row) {
      this.$confirm(`确定禁用菜单${row.menuName}吗？`, '禁用提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        disableMenu(row.id).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '禁用成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        })
      })
    }
  }
}
</script>
